using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.HtmlControls;

namespace TradingPlatform.IB.Utility
{
    public class TradingHtmlTable
    {
        private readonly HtmlTable _htmlTable;
        private static readonly Regex _numberRegex = new Regex(@"^[-+]?[0-9]*\.?[0-9]*$");

        public TradingHtmlTable()
        {
            _htmlTable = new HtmlTable();
            _htmlTable.Border = 2;
            _htmlTable.BorderColor = ColorTranslator.ToHtml(Color.Brown);
        }

        public void AddRow(string[] record)
        {
            HtmlTableRow htmlTableRow = new HtmlTableRow();

            foreach (string item in record)
            {
                HtmlTableCell htmlTableCell = new HtmlTableCell();
                htmlTableCell.InnerText = item;
                htmlTableCell.BorderColor = ColorTranslator.ToHtml(Color.Brown);

                if (item.Length>0 && _numberRegex.IsMatch(item))
                {
                    htmlTableCell.InnerText = double.Parse(item).ToString("N");

                    htmlTableCell.Align = "Right";
                    if (double.Parse(item)>0)
                    {
                        htmlTableCell.BgColor = ColorTranslator.ToHtml(Color.Green);
                    }
                    if (double.Parse(item) < 0)
                    {
                        htmlTableCell.BgColor = ColorTranslator.ToHtml(Color.Red);
                    }
                }

                htmlTableRow.Cells.Add(htmlTableCell);
            }

            _htmlTable.Rows.Add(htmlTableRow);
        }

        public void Clear()
        {
            _htmlTable.Rows.Clear();
        }

        public override string ToString()
        {
            string result;
            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    _htmlTable.RenderControl(htw);
                }
                sw.Flush();
                result = sw.ToString();
            }

            return result;
        }
    }
}
